package com.lrs.java.j2se_advanced.codec;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Map;

import junit.framework.TestCase;

import org.junit.Test;

public class TestByteConvertion extends TestCase{

	private Charset UTF_8 = Charset.forName("UTF-8");
	private Charset UTF_16 = Charset.forName("UTF-16");
	private Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
	private Charset US_ASCII = Charset.forName("US-ASCII");
	private Charset GB2312 = Charset.forName("GB2312");
	
	
	@Test
	public void testHello() {
		System.out.println("hello junit test");
	}
	
	@Test
	public void testBytesConvertion() {
		byte[] bytes = new byte[] {0x7, (byte)0xE8, 0x19, 0x02, (byte)0xC1, 0x29, 0x00, (byte)0xAF};
		
		print("00B1".getBytes().length);
		
		print('\u9ffd');
		
		String strDlt = new String(bytes);
		String strISO = new String(bytes, ISO_8859_1);
		String strAS = new String(bytes, US_ASCII);
		
		print(strDlt + strDlt.length());
		print(strISO + strISO.length());
		print(strAS + strAS.length());
		
		byte[] byteD = strDlt.getBytes();
		byte[] byteISO = strISO.getBytes();
		byte[] byteAS = strAS.getBytes();
		
		String strHex = Hex.encodeHexStr(bytes, true);
		
		print("end");
	}
	
	@Test
	public void testSupportedCharsets() {
		
		for(Map.Entry<String, Charset> entry: Charset.availableCharsets().entrySet()) {
			System.out.println(entry.getKey() + "  " + entry.getValue());
		}
		
	}
	
	@Test
	public void testASCIICharset() {
		byte[] as = new byte[]{0x00, 0x01, 0x02, 0x7E, 0x7F};
		
		String strAs = new String(as);
		byte[] asBack = strAs.getBytes();
		
		print(asBack);
	}
	
	@Test
	public void testGB2312() {
		
		byte[] gb2312 = new byte[] {(byte)0xA1, (byte)0xC0, (byte)0xA1, (byte)0xC1}; //±×
		
		String gb2312Str = new String(gb2312, GB2312);
		
		byte[] another = gb2312Str.getBytes(); //use default charset
		byte[] utf_8_bytes = "±×".getBytes(UTF_8);
		
		print(gb2312Str);
	}
	
	
	@Test
	public void testUTF8Encode() {
		String hello = "国";
		ByteBuffer bb = UTF_8.encode(hello);
		byte[] bytes = bb.array();
		
		print(UTF_8.decode(bb).toString());
		
		ByteBuffer bb_gb2312 = GB2312.encode(hello);
		byte[] bytes_gb2312 = bb_gb2312.array();
		
		print(GB2312.decode(bb_gb2312).toString());
		
		print("end");
		
	}
	
	@Test
	public void testJavaChar() {
		
		char a = '\u2122'; // ™
		char b = '™';
		char π = 'π';
		
		print(a);
		print((int)a); //8482
		print(π);
		
		String tm = "™";
		byte[] tmByte = tm.getBytes(UTF_16);
		
		print(Hex.encodeHex(tmByte));
	}
	
	@Test
	public void testTypeScope() {
		
		print(Float.MIN_VALUE);
		print(Float.MAX_VALUE);
		
		
	}
	
	
	public void print(Object obj) {
		System.out.println(obj);
	}
	
	
	
}
